from pocketbase import PocketBase
from pocketbase.services import AdminAuthResponse

from application.utils import get_rich_logger
from application.handle_exception import pb_operation_exception
from domain.authentication import Admin
from db.metastore import connect_with_pocketbase, admin_auth_via_client

logger = get_rich_logger()


def admin_create_via_client(client: PocketBase, new_admin: Admin):
    body_param = {
        "email": new_admin.email,
        "password": new_admin.password,
        "passwordConfirm": new_admin.password,
    }
    ret = client.admins.create(body_params=body_param)
    return ret


async def create_new_admin(
        auth: Admin,
        new_admin: Admin
):
    """
    Create a new admin.
    :param auth: admin authentication info
    :param new_admin: new admin info
    :return: new admin's data | raise http exception
    """
    with connect_with_pocketbase() as client:
        auth_rsp: AdminAuthResponse = admin_auth_via_client(
            client=client,
            admin=auth
        )
        logger.debug(f"Metastore admin authentication done. Response: {auth_rsp.admin, auth_rsp.token}")
        ret_admin = admin_create_via_client(
            client=client,
            new_admin=new_admin
        )
        logger.debug(f"New admin created.")
        if not ret_admin:
            raise pb_operation_exception
    return ret_admin
